#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
充值记录数据模型
"""

from database import db
from datetime import datetime
import uuid

class Recharge(db.Model):
    __tablename__ = 'recharges'
    
    id = db.Column(db.Integer, primary_key=True)
    recharge_no = db.Column(db.String(32), unique=True, nullable=False, comment='充值单号')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    
    # 充值信息
    package_type = db.Column(db.String(50), nullable=False, comment='充值套餐类型')
    amount = db.Column(db.DECIMAL(10, 2), nullable=False, comment='充值金额')
    bonus_amount = db.Column(db.DECIMAL(10, 2), default=0.00, comment='赠送金额')
    total_amount = db.Column(db.DECIMAL(10, 2), nullable=False, comment='到账总额')
    
    # 支付信息
    payment_method = db.Column(db.String(20), nullable=False, comment='支付方式：wechat微信，alipay支付宝')
    payment_status = db.Column(db.String(20), default='pending', comment='支付状态：pending待支付，paid已支付，failed失败，refunded已退款')
    paid_at = db.Column(db.DateTime, nullable=True, comment='支付时间')
    transaction_id = db.Column(db.String(100), nullable=True, comment='第三方交易号')
    
    # 优惠信息
    coupon_id = db.Column(db.Integer, nullable=True, comment='优惠券ID')
    discount_amount = db.Column(db.DECIMAL(10, 2), default=0.00, comment='优惠金额')
    
    # 系统字段
    status = db.Column(db.Integer, default=1, comment='状态：1正常，0异常')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    remark = db.Column(db.Text, nullable=True, comment='备注')
    
    def __init__(self, **kwargs):
        super(Recharge, self).__init__(**kwargs)
        if not self.recharge_no:
            self.recharge_no = self.generate_recharge_no()
    
    @staticmethod
    def generate_recharge_no():
        """生成充值单号"""
        prefix = datetime.now().strftime('%Y%m%d')
        suffix = str(uuid.uuid4()).replace('-', '')[:8].upper()
        return f'RC{prefix}{suffix}'
    
    def to_dict(self):
        return {
            'id': self.id,
            'recharge_no': self.recharge_no,
            'user_id': self.user_id,
            'package_type': self.package_type,
            'amount': float(self.amount),
            'bonus_amount': float(self.bonus_amount),
            'total_amount': float(self.total_amount),
            'payment_method': self.payment_method,
            'payment_status': self.payment_status,
            'paid_at': self.paid_at.isoformat() if self.paid_at else None,
            'transaction_id': self.transaction_id,
            'coupon_id': self.coupon_id,
            'discount_amount': float(self.discount_amount),
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'remark': self.remark,
            'user': self.user.to_dict() if self.user else None
        }
    
    def __repr__(self):
        return f'<Recharge {self.recharge_no}>'